package com.baidu.validator;

import com.baidu.captcha.CaptchaRender;
import com.baidu.captcha.Touclick;
import com.baidu.config.MainConfig;
import com.baidu.emus.ErrorCode;
import com.baidu.model.Invite;
import com.baidu.model.SysUser;
import com.baidu.util.TestUtil;
import com.jfinal.core.Controller;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.ehcache.CacheKit;
import com.jfinal.validate.Validator;

public class RegisterValidator extends Validator{
	
	private static final String msg = "message";
	
	@Override
	protected void validate(Controller c) {
		setShortCircuit(true);
        validateRequired("userName", msg, "请您输入用户名!");
        validateRequired("password", msg, "请您输入密码!");
        validateRequired("email", msg, "请您输入邮箱!");
        validateEmail("email", msg, "请输入正确邮箱地址");
       // validateRequired("captcha", msg, "请您输入验证码!");
//        String captcha = c.getPara("captcha");
//        String md5Code = CacheKit.get("CaptchaFilter", CaptchaRender.DEFAULT_CAPTCHA_MD5_CODE_KEY + c.getSession().getId());
//        if(!CaptchaRender.validate(md5Code, captcha)){
//			addError(msg, "验证码错误,请重新输入!");
//        }
        /*if(!CaptchaRender.validate(md5Code, captcha)){
			addError(msg, "验证码错误,请重新输入!");
        }*/
        Boolean checkCaptcha = Touclick.check( MainConfig.custom_prop.get("website_key"), MainConfig.custom_prop.get("private_key"),
        		c.getPara("check_key"), c.getPara("check_address"), null, null, null);
        if(!checkCaptcha){
        	addError(msg, "验证码错误,请重新输入!");
        }
        if(MainConfig.custom_prop.getBoolean("isInvite")){
        	validateRequired("inviteCode", msg, "请输入邀请码");
        	String inviteCode = c.getPara("inviteCode");
        	if(StrKit.notBlank(inviteCode)){
        		Invite tmp = Invite.dao.findFirst("select * from sys_invite where (isValid=0 or isUsed=1) and code=?", inviteCode);
        		if(tmp != null){//邀请码无效或已被使用
        			addError(msg, "邀请码无效或已被使用！");
        		}
        	}
        }
        String userName = c.getPara("userName");
//        String password = c.getPara("password");
        String email = c.getPara("email");
        if(StrKit.notBlank(userName)){
        	SysUser tmp = SysUser.dao.findFirst("select * from sys_user where userName=?", userName);
        	if(tmp != null){//用户名或邮箱已存在
        		addError(msg, "用户名已被注册，请重新输入！");
        	}
        }
        if(StrKit.notBlank(email)){
        	SysUser tmp = SysUser.dao.findFirst("select * from sys_user where email=?", email);
        	if(tmp != null){//用户名或邮箱已存在
        		addError(msg, "邮箱已被注册，请重新输入！");
        	}
        }
	}

	@Override
	protected void handleError(Controller c) {
		c.setAttr("status",ErrorCode.registerError.getCode());
		c.keepPara();
        c.render("register.html");
	}

}
